import * as React from 'react';
import { message, Tooltip, Card, Button, Tag, Popconfirm, Icon } from 'antd';
import { get, filter, map } from 'lodash';

import makeHoc from 'components/common/makeHoc';
import CustomModal from 'components/common/CustomModal';
import { toggleTagCheck, initSelectedItems } from 'actions/tag';

import { isLoading } from 'utils/utils';
import ACTIONS from 'constants/knowledge';

import LoadableComponent from 'components/common/LoadableComponent';
const LoadableTagIndex = LoadableComponent(() => import('pages/tag/Index'));

interface EditTagProps {
  dispatch: (action: any) => any;
  handleCallback: (ownTags: any[]) => any;
  loadingGroup: any;
  knowledgeId: number;
  ownTags: any[];
  selectedTags: any[];
}

interface EditTagState {
  isSelectTag: boolean;
}

class EditTag extends React.Component<EditTagProps, EditTagState> {
  static defaultProps: EditTagProps = {
    dispatch: () => {},
    handleCallback: () => {},
    loadingGroup: {},
    knowledgeId: 0,
    ownTags: [],
    selectedTags: [],
  };
  constructor(props: EditTagProps) {
    super(props);
    this.state = {
      isSelectTag: false,
    };
  }

  componentDidMount() {
    const { ownTags } = this.props;
    this.handleInitSelectedItems(ownTags);
  }

  componentWillReceiveProps(nextProps: any) {
    const { knowledgeId } = nextProps;
    const { knowledgeId: oldKnowledgeId } = this.props;

    // 标签选择更新
    if (knowledgeId !== oldKnowledgeId) {
      this.handleInitSelectedItems(nextProps.ownTags);
    } else {
      this.handleInitSelectedItems(nextProps.selectedTags);
    }
  }

  handleInitSelectedItems = (ownItems: any[]) => {
    this.props.dispatch(initSelectedItems(ownItems));
  };

  handleOpenModal = () => {
    this.setState({
      isSelectTag: true,
    });
  };

  handleCloseModal = () => {
    this.setState({
      isSelectTag: false,
    });
  };

  // 从选择列表删除
  handleTrashItemTag = (target: any) => {
    this.props.dispatch(toggleTagCheck(target, false));
  };

  // 把tag从知识点db删除
  removeTag = (tagId: number) => {
    const { ownTags, handleCallback } = this.props;
    const leftTags = filter(ownTags, (item: any) => item.id !== tagId);

    handleCallback(leftTags);
  };

  handleSubmit = () => {
    const { loadingGroup, selectedTags, handleCallback } = this.props;

    if (selectedTags.length && !isLoading(loadingGroup, ACTIONS.SAVE_TAG)) {
      handleCallback(selectedTags);
    }

    this.handleCloseModal();
  };

  renderItems() {
    const { selectedTags } = this.props;
    let renderHtml = null;

    if (selectedTags.length) {
      renderHtml = selectedTags.map((item: any) => {
        return (
          <Tooltip key={String(item.id)} title={item.description}>
            <Tag closable={false}>
              {item.enName}
              &nbsp;&nbsp;
              <Popconfirm
                title="移除此标签？"
                placement="bottom"
                onConfirm={() => {
                  this.removeTag(item.id);
                }}
                okText="确定"
                cancelText="取消">
                <Icon type="cross" />
              </Popconfirm>
            </Tag>
          </Tooltip>
        );
      });
    } else {
      renderHtml = (
        <p className="loading-placeholder">
          <Icon type="frown-o" />
          &nbsp;还没有数据，&nbsp;
          <a href="javascript:void(0);" onClick={this.handleOpenModal}>
            <Icon type="plus" />
            添加
          </a>
        </p>
      );
    }

    return <div className="custom-tags no-click">{renderHtml}</div>;
  }

  renderFooterSelected = () => {
    const { selectedTags } = this.props;

    return (
      <Card title="选择1个标签" style={{ textAlign: 'left' }}>
        {selectedTags.length > 0 ? (
          selectedTags.map((tag: any) => {
            return (
              <Tooltip title={tag.description} key={tag.id}>
                <Tag key={tag.id}>
                  {tag.enName}
                  &nbsp;&nbsp;
                  <Icon
                    type="cross"
                    onClick={e => {
                      e.stopPropagation();
                      this.handleTrashItemTag(tag);
                    }}
                  />
                </Tag>
              </Tooltip>
            );
          })
        ) : (
          <p className="loading-placeholder">
            <Icon type="frown-o" />
            &nbsp; 还没有标签哦
          </p>
        )}
      </Card>
    );
  };

  renderFooterActions = () => {
    const { loadingGroup, selectedTags } = this.props;

    return (
      <div style={{ margin: 24 }}>
        <Button
          key="submit"
          type="primary"
          size="large"
          loading={isLoading(loadingGroup, ACTIONS.SAVE_TAG)}
          disabled={selectedTags.length === 0}
          onClick={this.handleSubmit}>
          保存
        </Button>
      </div>
    );
  };

  render() {
    return (
      <div>
        {this.state.isSelectTag && (
          <CustomModal
            width={800}
            footer={
              <React.Fragment>
                {this.renderFooterSelected()}
                {this.renderFooterActions()}
              </React.Fragment>
            }>
            <LoadableTagIndex selectMax={1} doSelect={true} />
          </CustomModal>
        )}
        {this.renderItems()}
      </div>
    );
  }
}

interface OwnProps {
  ownTags: any[];
  knowledgeId: number;
  handleCallback: (ownTags: any[]) => any;
}

function mapStateToProps(state: any, ownProps: OwnProps) {
  const { loadingGroup } = state;
  const { selectedTags } = state.tag;
  const { ownTags, knowledgeId, handleCallback } = ownProps;

  return {
    ownTags,
    knowledgeId,
    loadingGroup,
    selectedTags,
    handleCallback,
  };
}

export default makeHoc(mapStateToProps)(EditTag, {
  addTag() {
    this.handleOpenModal();
  },
});
